<?php

declare(strict_types=1);

namespace App\Admin\Service\Setting;

use App\Admin\Mapper\Setting\SettingCrontabMapper;
use Newbie\Abstracts\AbstractService;
use Newbie\Cache\Redis;
use Newbie\Crontab\NewbieCrontab;
use Newbie\Crontab\NewbieExecutor;


class SettingCrontabService extends AbstractService {
    /**
     * @var SettingCrontabMapper
     */
    public $mapper;

    /**
     * @var string
     */
    protected string $prefix = '';

    /**
     * @var Redis $redis
     */
    protected Redis $redis;

    /**
     * @param SettingCrontabMapper $mapper
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function __construct (SettingCrontabMapper $mapper) {
        $this->mapper = $mapper;
        $this->redis  = container()->get(Redis::class);
    }

    /**
     * 保存
     * @param array $data
     * @return int
     */
    public function save (array $data): int {
        $id = parent::save($data);
        $this->redis->del($this->prefix . 'crontab');
        return $id;
    }

    /**
     * 更新
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function update (int $id, array $data): bool {
        $res = parent::update($id, $data);
        $this->redis->del($this->prefix . 'crontab');
        return $res;
    }

    /**
     * 删除
     * @param string $ids
     * @return bool
     */
    public function delete (string $ids): bool {
        $res = parent::delete($ids);
        $this->redis->del($this->prefix . 'crontab');
        return $res;
    }

    /**
     * 立即执行一次定时任务
     * @param $id
     * @return bool|null
     */
    public function run ($id): ?bool {
        $crontab = new NewbieCrontab();
        $model   = $this->read($id);
        $crontab->setCallback($model->target);
        $crontab->setType($model->type);
        $crontab->setEnable(true);
        $crontab->setCrontabId($model->id);
        $crontab->setName($model->name);
        $crontab->setParameter($model->parameter ?: '');
        $crontab->setRule($model->rule);
        $executor = $this->container->get(NewbieExecutor::class);
        return $executor->executeOne($crontab);
    }
}